package com.zhaorui.component;

import com.zhaorui.entity.ZR;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import sun.plugin2.message.Message;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@RestControllerAdvice
/**
 * 标志异常类：@RestControllerAdvice；
 * 全局异常拦截
 */
public class CustomControllerAdvice {
    //参数：数据异常捕获
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ZR dealParam(MethodArgumentNotValidException e) {
        //获取封装异常信息
        BindingResult bindingResult = e.getBindingResult ();
        //获取所有具体异常对象
        List<FieldError> fieldErrors = bindingResult.getFieldErrors ();
        HashMap map = new HashMap ();
        fieldErrors.forEach (fieldError -> {
            map.put (fieldError.getField (), fieldError.getDefaultMessage ());
        });
        return new ZR (-1000, "参数不合法", map);
    }

    //sql异常
    @ExceptionHandler(BusinessException.class)
    public ZR dealSql(BusinessException e) {
        return new ZR (-1000, "系统维护，请稍后在试...", e.getMessage ());
    }

    //导入异常
    @ExceptionHandler(IOException.class)
    public ZR ioExcel(IOException e) {
        return new ZR (-1000, "导入失败", e.getMessage ());
    }

    //捕获业务未知异常
    @ExceptionHandler(Exception.class)
    public ZR work(Exception e) {
        return new ZR (-1000, "未知异常", e.getMessage ());
    }

}
